package com.aqie.meet.ui.talents;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.aqie.libcommon.adapter.CommonAdapter2;
import com.aqie.libcommon.adapter.CommonViewHolder2;
import com.aqie.libcommon.app.BaseApplication;
import com.aqie.libcommon.app.BaseFragment;
import com.aqie.libcommon.utils.CommonUtils;
import com.aqie.libcommon.view.EmptyView;
import com.aqie.libcommon.view.UMExpandLayout;
import com.aqie.libfactory.model.api.PageList;
import com.aqie.libfactory.model.api.RspModel;
import com.aqie.libfactory.model.api.chat.ChatPermission;
import com.aqie.libfactory.model.api.websocket.WebsocketLoginModel;
import com.aqie.libfactory.model.db.User;
import com.aqie.libfactory.net.Network;
import com.aqie.libfactory.net.RemoteService;
import com.aqie.libfactory.persistence.Account;
import com.aqie.libnavanotation.FragmentDestination;
import com.aqie.meet.R;
import com.aqie.meet.helper.NavHelper;
import com.aqie.meet.ui.chat.MessageActivity;
import com.aqie.meet.ui.login.AccountActivity;
import com.aqie.meet.ui.my.FriendHomePageActivity;
import com.aqie.meet.ui.search.SearchActivity;
import com.aqie.meet.utils.Utils;
import com.aqie.meet.view.AImageView;
import com.zhangke.websocket.WebSocketHandler;
import com.zhangke.websocket.WebSocketManager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import butterknife.BindView;
import butterknife.OnClick;
import circletextimage.viviant.com.circletextimagelib.view.CircleTextImage;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@FragmentDestination(pageUrl = "main/tabs/talents", asStarter = true,needLogin = false)
public class TalentsFragment extends BaseFragment {


    @BindView(R.id.recycler_view)
    RecyclerView mRecycleView;

    @BindView(R.id.empty_view)
    EmptyView mEmptyView;

    @BindView(R.id.im_search)
    ImageView mSearch;

    private NavHelper<Integer> mNavHelper;

    private List<User> mList = new ArrayList<>();
    private CommonAdapter2<User> mAdapter;

    // 聊天权限相关
    private ChatPermission chatPermission = null;
    final CountDownLatch count = new CountDownLatch(1);

    WebSocketManager manager = null;
    // Recycle 第一个可视Item
    private int firstVisibleItemPosition = 0;



    public TalentsFragment() {
        // 进行websocket 登录
        WebsocketLoginModel loginModel = new WebsocketLoginModel();
        if(Account.getUserId() != null && !TextUtils.isEmpty(Account.getUserId())){
            // BaseApplication.showToast("进行websocket 登录" + Account.getUserId());
            loginModel.setExpand(Account.getUserId());
            manager = WebSocketHandler.getDefault();
            manager.send(JSONArray.toJSON(loginModel).toString());
        }

    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.talents_fragment;
    }


    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        initView();
    }

    private void initView() {
        mRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecycleView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager)mRecycleView.getLayoutManager();
        mAdapter = new CommonAdapter2<>(mList, new CommonAdapter2.OnBindDataListener<User>() {
            @Override
            public void onBindViewHolder(User model, CommonViewHolder2 viewHolder, int type, int position) {
                fillData(model, viewHolder);
                UMExpandLayout details = viewHolder.getView(R.id.setting_about_content);
                // 当前第一个可视区域则展示
                if(position == firstVisibleItemPosition){
                    // details.setVisibility(View.VISIBLE);
                    // BaseApplication.showToast(firstVisibleItemPosition + " " + position);
                    // mAdapter.notifyDataSetChanged();
                }
                viewHolder.getView(R.id.tag_title).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewHolder.toggle(R.id.setting_about_content);
                    }
                });
                // 切换
                viewHolder.getView(R.id.icon_up).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewHolder.setVisibility(R.id.icon_down, View.VISIBLE);
                        viewHolder.setVisibility(R.id.icon_up, View.GONE);
                        viewHolder.setVisibility(R.id.setting_about_content, View.GONE);
                    }
                });
                viewHolder.getView(R.id.icon_down).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewHolder.setVisibility(R.id.icon_up, View.VISIBLE);
                        viewHolder.setVisibility(R.id.icon_down, View.GONE);
                        viewHolder.setVisibility(R.id.setting_about_content, View.VISIBLE);
                    }
                });
                // 跳转聊天
                viewHolder.getView(R.id.btn_send_message).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        getChatPermission(model.getUserId(),model.getUsername());

                    }
                });
                // 跳转详情
                viewHolder.getView(R.id.tag_avatar_true).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), FriendHomePageActivity.class);
                        intent.putExtra("talentsId", model.getUserId());
                        intent.putExtra("username", model.getUsername());
                        intent.putExtra("isBoolFriend", model.isBoolFriend());
                        startActivity(intent);
                    }
                });

                // 发送添加好友请求
                viewHolder.getView(R.id.btn_add_friend).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // BaseApplication.showToast("添加好友");
                        addFriend(model.getUserId());
                    }
                });

            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.talents_item;
            }
        });
        mRecycleView.setAdapter(mAdapter);
        //监听列表滑动
        mRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                assert linearLayoutManager != null;
                firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
                // mAdapter.notifyDataSetChanged();
            }
        });
    }

    private void getChatPermission(String friendId, String username) {
        RemoteService service = Network.remote();
        Call<RspModel<ChatPermission>> call = service.chatPermission(friendId);
        call.enqueue(new Callback<RspModel<ChatPermission>>() {
            @Override
            public void onResponse(Call<RspModel<ChatPermission>> call, Response<RspModel<ChatPermission>> response) {
                RspModel<ChatPermission> body = response.body();
                //String rspString = SimpleJsonTool.toJson(body); Log.e(TAG, rspString);Log.e(TAG, friendId);

                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }
                if(body !=null && body.success()){
                    chatPermission = body.getData();
                    // BaseApplication.showToast("获取权限成功");
                    if(chatPermission.isBoolChat()){
                        MessageActivity.show(getActivity(), friendId, username, true);
                    } else {
                        MessageActivity.show(getActivity(), friendId, username, false);
                        // BaseApplication.showToast("暂无聊天权限");
                    }
                }
            }

            @Override
            public void onFailure(Call<RspModel<ChatPermission>> call, Throwable t) {

            }
        });
    }

    private void addFriend(String friendId) {
        RemoteService service = Network.remote();
        Call<RspModel<Boolean>> call = service.friendRequestSend(friendId,null,null);
        call.enqueue(new Callback<RspModel<Boolean>>() {
            @Override
            public void onResponse(Call<RspModel<Boolean>> call, Response<RspModel<Boolean>> response) {
                RspModel<Boolean> body = response.body();

                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }
                if(body !=null && body.success()){
                    BaseApplication.showToast("发送成功");
                }
            }

            @Override
            public void onFailure(Call<RspModel<Boolean>> call, Throwable t) {

            }
        });
    }

    private void fillData(User model, CommonViewHolder2 viewHolder) {
        CircleTextImage mCircleTextImage = viewHolder.getView(R.id.tag_avatar);
        AImageView mTrueAvatar = viewHolder.getView(R.id.tag_avatar_true);
        if(model != null && model.getAvatar() != null){
            mTrueAvatar.setVisibility(View.VISIBLE);
            mTrueAvatar.setImageUrl(model.getAvatar());
            mCircleTextImage.setVisibility(View.GONE);
        } else {
            if(model != null && model.getUsername() != null && model.getUsername().length() > 0){
                mCircleTextImage.setText4CircleImage(Utils.getName(model.getUsername()));
            }
        }
        viewHolder.setText(R.id.tag_title, model.getUsername() + " | " + model.getTrade() + " " + model.getPosition());
        viewHolder.setText(R.id.tag_desc, model.getCity() + " " + model.getWorkingYears() + "年工作经验");

        if(TextUtils.isEmpty(model.getCity()) || model.getWorkingYears() == null ){
            viewHolder.goneIfEmpty(R.id.tag_desc);
        }

        // 已经是好友 隐藏添加
        if(model.isBoolFriend()){
            viewHolder.goneIfEmpty(R.id.btn_add_friend);
        }
        viewHolder.setText(R.id.et_resource, model.getAnswerOne());
        viewHolder.setText(R.id.et_need, model.getAnswerTwo());
        viewHolder.setText(R.id.et_know, model.getAnswerThree());
    }

    @Override
    protected void initData() {
        super.initData();
        // getTalentsList();
    }

    @Override
    public void onResume() {
        super.onResume();
        getTalentsList();
    }

    private void getTalentsList() {
        RemoteService service = Network.remote();
        Call<RspModel<PageList<User>>> call = service.talents("",1,1000);
        call.enqueue(new Callback<RspModel<PageList<User>>>() {
            @Override
            public void onResponse(Call<RspModel<PageList<User>>> call, Response<RspModel<PageList<User>>> response) {
                RspModel<PageList<User>> body = response.body();
                if(body !=null && body.success()){
                    PageList<User> talents = body.getData();
                    //String rspString = SimpleJsonTool.toJson(talents); Log.e(TAG, rspString);
                    if(talents.getTotal() == 0) {
                        mRecycleView.setVisibility(View.GONE);
                        mEmptyView.setVisibility(View.VISIBLE);
                    } else {
                        mRecycleView.setVisibility(View.VISIBLE);
                        mEmptyView.setVisibility(View.GONE);
                        if (mList.size() > 0) {
                            mList.clear();
                        }
                        mList.addAll(talents.getRecords());
                        mAdapter.notifyDataSetChanged();
                        // Log.e(TAG, "talent list:" + mList.toString());
                    }
                }else {
                    Log.e(TAG, "request fail: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<RspModel<PageList<User>>> call, Throwable t) {
                Log.e(TAG, "request fail: onFailure");
            }
        });
    }



    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (!CommonUtils.isEmpty(mList)) {
                getTalentsList();
            }
        }
    }

    // 点击搜索人才按钮
    @OnClick(R.id.im_search)
    void onSearchMenuClick() {
        SearchActivity.show(getActivity(), SearchActivity.TYPE_TALENT);
    }

}